package com.hunantv.mglive.ui.live;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.hunantv.mglive.R;
import com.hunantv.mglive.common.BaseActivity;
import com.hunantv.mglive.common.BuildConfig;
import com.hunantv.mglive.common.Constant;
import com.hunantv.mglive.common.FormEncodingBuilderEx;
import com.hunantv.mglive.data.LiveDetailModel;
import com.hunantv.mglive.data.ResultModel;
import com.hunantv.mglive.data.StarModel;
import com.hunantv.mglive.data.live.ChatData;
import com.hunantv.mglive.utils.StringUtil;
import com.hunantv.mglive.utils.Toast;
import com.hunantv.mglive.widget.GiftViewAnim;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class StarDetailActivity extends BaseActivity implements onStarDetailVideoCallBack, ChatViewCallback, StarLiveDetailCentreFragment.ICenterViewCallback {
    public static final String KEY_STAR_ID = "KEY_STAR_ID";
    public static final String KEY_LID = "KEY_LID";
    public static final String KEY_TYPE = "KEY_TYPE";
    public static final String KEY_TITLE = "KEY_TITLE";
    public static final String KEY_DYNAMIC_VIDEO_ID = "KEY_DYNAMIC_VIDEO_ID";
    private String mStarId;
    private String mLid;
    private String mType;
    private String mCurrId;
    private int mHeight;
    private boolean mIsLand;
    private View mVChat;
//    private OnTouchListener mListener;
    private ChatFragment mChatFragment;
    private GiftFragment mGiftFragment;
    private StarDetailInfoFragment mStarDetailInfoFragment;

    private GiftViewAnim mGiftViewAnim;
    private LiveDetailModel mLiveDetailModel;

    private int mWidth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        ViewGroup mViewGroup = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.activity_star_detail, null);
        setContentView(mViewGroup);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        setLayoutParams(mIsLand);
        mGiftViewAnim = new GiftViewAnim(getContext(), mViewGroup);
        Intent intent = getIntent();
        mStarId = intent.getStringExtra(KEY_STAR_ID);
        mCurrId = intent.getStringExtra(KEY_DYNAMIC_VIDEO_ID);
        if (StringUtil.isNullorEmpty(mStarId)) {
            mLid = intent.getStringExtra(KEY_LID);
            mType = intent.getStringExtra(KEY_TYPE);
        }

        mStarDetailInfoFragment = (StarDetailInfoFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_star_detail_info);
        mStarDetailInfoFragment.setOnStarDetailVideoCallBack(this);

        setGifView();
        mVChat = findViewById(R.id.ll_star_detail_chat_view);
        mChatFragment = (ChatFragment) getSupportFragmentManager().findFragmentById(R.id.fragmenrt_star_chat);
        mChatFragment.setChatViewCallback(this);
        mChatFragment.setVideoViewListener(this);
        loadStarModel();
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            changeToLandView();
        }
    }

    public void loadStarModel() {
        if (mStarId != null && !"".equals(mStarId)) {
            Map<String, String> body = new FormEncodingBuilderEx()
                    .add("uid", mStarId)
                    .build();
            post(BuildConfig.URL_STAR_INFO, body);
        } else if (!StringUtil.isNullorEmpty(mLid)) {
            Map<String, String> requestBody = new FormEncodingBuilderEx().add(Constant.KEY_LID, mLid).add(Constant.KEY_TYPE, mType).build();
            post(BuildConfig.URL_GET_DETAIL, requestBody);
        }
    }

    public void setGifView() {
        mGiftFragment = (GiftFragment) getSupportFragmentManager().findFragmentById(R.id.fragmenrt_gift);
        mGiftFragment.setGiftAnimListener(this);
    }

//    public void registerTouchListener(OnTouchListener listener) {
//        this.mListener = listener;
//    }

    private void setLayoutParams(boolean island) {
        View v = findViewById(R.id.ll_star_detail_info);
        RelativeLayout.LayoutParams ps = (RelativeLayout.LayoutParams) v.getLayoutParams();
        if (!island) {
            //按比例缩放直播窗体
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            int width = dm.widthPixels > dm.heightPixels ? dm.heightPixels : dm.widthPixels;
            mWidth = width;
            mHeight = (int) (width * 0.75);
            ps.height = mHeight;//0.56
        } else {
            ps.height = RelativeLayout.LayoutParams.MATCH_PARENT;
            ps.width = RelativeLayout.LayoutParams.MATCH_PARENT;
        }
        v.setLayoutParams(ps);
    }

    private void changeToPortraitView() {
        if (mGiftFragment != null) {
            mGiftFragment.hideGiftView();
            mGiftFragment.onScreenChange(false);
        }
        mIsLand = false;
//        mVChat.setVisibility(View.VISIBLE);
        setLayoutParams(false);
        if (mStarDetailInfoFragment != null) {
            mStarDetailInfoFragment.screenOrietantionChanged(false);
        }
        if (mChatFragment != null) {
            mChatFragment.screenOrietantionChanged(false);
        }
    }

    private void changeToLandView() {
        if (mGiftFragment != null) {
            mGiftFragment.hideGiftView();
            mGiftFragment.onScreenChange(true);
        }
        mIsLand = true;
        setLayoutParams(true);
        if (mStarDetailInfoFragment != null) {
            mStarDetailInfoFragment.screenOrietantionChanged(true);
        }
        if (mChatFragment != null) {
            mChatFragment.screenOrietantionChanged(true);
        }
//        mVChat.setVisibility(View.GONE);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
//        if (mListener != null && event.getY() < mHeight) {
//            return mListener.onTouch(event);
//        }
        return super.onTouchEvent(event);
    }

    @Override
    public void followStarChange(StarModel starModel) {
        String hotValue = !StringUtil.isNullorEmpty(starModel.getHotValue()) ? starModel.getHotValue() : starModel.getHots();
        mChatFragment.updateHotValue(hotValue);
    }

    @Override
    public void showGift() {
        if (mGiftFragment != null) {
            mGiftFragment.showGiftView();
        }
    }

    @Override
    public void startAnim(String image, String text, int fromx, int fromy) {
        mGiftViewAnim.startGiftViewAnim(image, text, fromx, mWidth / 2, fromy, mHeight / 2);
    }

    @Override
    public void hasMsg(ChatData chatData) {
        if (mStarDetailInfoFragment != null) {
            mStarDetailInfoFragment.hasMsg(chatData);
        }
    }

    @Override
    public void changeOnline(String changeStr) {

    }

    @Override
    public void changeGiftView(boolean isDisplay) {
        if (mGiftFragment != null) {
            if (isDisplay) {
                mGiftFragment.showGiftView();
            } else {
                mGiftFragment.hideGiftView();
            }
        }
    }

    @Override
    public void changeStarHotValue(long hotValue) {

    }

    @Override
    public void pauseVideo() {
        if (mStarDetailInfoFragment != null) {
            mStarDetailInfoFragment.pauseVideo();
        }
    }

    @Override
    public void starVideo() {
        if (mStarDetailInfoFragment != null) {
            mStarDetailInfoFragment.resumVideo();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

//    public interface OnTouchListener {
//
//        boolean onTouch(MotionEvent ev);
//    }

    @Override
    public void onSucceed(String url, ResultModel resultModel) throws JSONException {
        if (BuildConfig.URL_STAR_INFO.equals(url)) {
            StarModel starModel = (StarModel) resultModel.getDataModel();
            mStarDetailInfoFragment.setStarInfo(starModel, mCurrId);
            mChatFragment.setTitle(starModel.getNickName() + "-个人空间");
            mChatFragment.setStarInfo(starModel);
            mGiftFragment.setStarInfo(starModel);
            if (null != mLiveDetailModel && !StringUtil.isNullorEmpty(mLiveDetailModel.getChatFlag())) {
                mChatFragment.setData(mLiveDetailModel.getChatFlag(), mLiveDetailModel.getChatKey());
            } else {
                mChatFragment.setData(ChatFragment.TYPE_VIDEO_OFF, starModel.getUid());
            }
        } else if (BuildConfig.URL_GET_DETAIL.equals(url)) {
            mLiveDetailModel = (LiveDetailModel) resultModel.getDataModel();
            if (mLiveDetailModel != null && mLiveDetailModel.getUsers() != null && mLiveDetailModel.getUsers().size() > 0) {
                StarModel starModel = mLiveDetailModel.getUsers().get(0);
                mStarId = starModel.getUid();
                Map<String, String> body = new FormEncodingBuilderEx()
                        .add("uid", mStarId)
                        .add("token", getToken())
                        .build();
                post(BuildConfig.URL_STAR_INFO, body);
            }
        }
        super.onSucceed(url, resultModel);
    }

    @Override
    public void onFailure(String url, ResultModel resultModel) {
        super.onFailure(url, resultModel);
        Toast.makeText(getContext(), resultModel.getMsg(), Toast.LENGTH_SHORT).show();
    }


    @Override
    public Object asyncExecute(String url, ResultModel resultModel) {
        if (BuildConfig.URL_STAR_INFO.equals(url)) {
            StarModel starModels = JSON.parseObject(resultModel.getData(), StarModel.class);
            List<String> tagsjsons = starModels.getTags();
            if (tagsjsons != null && tagsjsons.size() > 0) {
                try {
                    ArrayList<String> tags = new ArrayList<String>();
                    for (String tagjson : tagsjsons) {

                        JSONObject json = new JSONObject(tagjson);
                        if (!json.isNull("name")) {
                            tags.add(json.get("name").toString());
                        }
                    }
                    starModels.setTags(tags);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            return starModels;
        } else if (BuildConfig.URL_GET_DETAIL.equals(url)) {
            return JSON.parseObject(resultModel.getData(), LiveDetailModel.class);
        }
        return super.asyncExecute(url, resultModel);
    }


    @Override
    public void finish() {
        getMqtt().stopMQTTService();
        super.finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (mGiftFragment.onBackpressed()) {
                return true;
            }
            if (mChatFragment != null && mChatFragment.onBackPressed()) {
                return true;
            }

            if (mStarDetailInfoFragment != null && mStarDetailInfoFragment.onBackPressed()) {
                return true;
            }
//            if (mChatFragment != null) {
//                mChatFragment.onFinishActivity();
//            }

        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            changeToLandView();
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            changeToPortraitView();
        }
    }

    @Override
    protected void onDestroy() {
        //释放引用
//        mStarDetailInfoFragment.setOnStarDetailVideoCallBack(null);
//        mChatFragment.setChatViewCallback(null);
//        mChatFragment.setVideoViewListener(null);
//        mGiftFragment.setGiftAnimListener(null);
//        mStarDetailInfoFragment.onDestroy();
//        mStarDetailInfoFragment = null;
//        mChatFragment.onDestroy();
//        mChatFragment = null;
//        mGiftFragment.onDestroy();
//        mGiftFragment = null;
        super.onDestroy();
    }
}
